<template>
  <view class="map-box">
    <div id="js-container" class="_map-box">正在加载中 ...</div>
  </view>
</template>

<script>
import {gdMapKey as MapKey,gdMapCityName as MapCityName} from '@/common/variable'
  import { getFrontList, gpGpinfo } from '@/common/request.js'
import {routerWebViewGd} from '@/common/util'
  export default {
    name: 'Map',
    data() {
      return {
        center: [120.218866, 30.287668], //中心点
      }
    },
    async created() {
      function remoteLoad(url, hasCallback) {
        return createScript(url)
        /**
         * 创建script
         * @param url
         * @returns {Promise}
         */
        function createScript(url) {
          const scriptElement = document.createElement('script')
          document.body.appendChild(scriptElement)
          const promise = new Promise((resolve, reject) => {
            scriptElement.addEventListener(
              'load',
              (e) => {
                removeScript(scriptElement)
                if (!hasCallback) {
                  resolve(e)
                }
              },
              false
            )

            scriptElement.addEventListener(
              'error',
              (e) => {
                removeScript(scriptElement)
                reject(e)
              },
              false
            )

            if (hasCallback) {
              window.____callback____ = function () {
                resolve()
                window.____callback____ = null
              }
            }
          })

          if (hasCallback) {
            url += '&callback=____callback____'
          }

          scriptElement.src = url

          return promise
        }

        /**
         * 移除script标签
         * @param scriptElement script dom
         */
        function removeScript(scriptElement) {
          document.body.removeChild(scriptElement)
        }
      }
      // 已载入高德地图API，则直接初始化地图
      const params = { frontAreaCode: this.frontAreaCode, frontPublic: 1 }
      if (window.AMap && window.AMapUI) {
        this.initMap()
      } else {
        await remoteLoad(
          `https://webapi.amap.com/maps?v=1.4.4&key=${MapKey}&plugin=AMap.Geocoder,AMap.PlaceSearch,AMap.ToolBar`
        )
        await remoteLoad('https://webapi.amap.com/ui/1.0/main.js')
        this.initMap()
      }
    },
    methods: {
      // 实例化地图
      initMap() {
        const AMapUI = (this.AMapUI = window.AMapUI)
        const AMap = (this.AMap = window.AMap)
        const that = this
        AMapUI.loadUI(['misc/PositionPicker'], (PositionPicker) => {
          const mapConfig = {
            center: that.center,
            zoom: 14,
            cityName: MapCityName,
          }
          const map = new AMap.Map('js-container', mapConfig)
          const list = that.covers
          const markers = []
          var marker = new AMap.Marker({
            icon: new AMap.Icon({
              image: '../../../static/img/marker.png',
              size: new AMap.Size(30, 30), //图标大小
              imageSize: new AMap.Size(30, 30),
            }),
            offset: new AMap.Pixel(-10, -10),
          })
          //鼠标点击marker弹出自定义的信息窗体
          marker.on('click', function (e) {
            //console.log(e)
          })
          markers.push(marker)
          map.setCenter(that.center)
          map.on('click', function (e) {
            map.clearInfoWindow()
          })
          var infoWindow = new AMap.InfoWindow({
            isCustom: true, //使用自定义窗体
            offset: new AMap.Pixel(16, -30),
          })

          //构建自定义信息窗体
          function createInfoWindow(content) {
            var info = document.createElement('div')
            info.style.background = '#FFFFFF'
            info.style.width = '250px'
            info.style.height = '170px'
            info.style.textAlign = 'left'
            info.style.color = '#FFFFFF'
            info.style.padding = '16px'
            info.innerHTML = content
            return info
          }

          //关闭信息窗体
          function closeInfoWindow() {
            map.clearInfoWindow()
          }

          // 创建地图拖拽
          const positionPicker = new PositionPicker({
            mode: 'dragMarker', // 设定为拖拽地图模式，可选'dragMap','dragMarker'，默认为'dragMap'
            map: map, // 依赖地图对象
          })

          // 拖拽完成发送自定义 drag 事件
          positionPicker.on('success', (positionResult) => {
            this.$emit('drag', {
              address:
                positionResult.regeocode.addressComponent.district +
                positionResult.regeocode.addressComponent.township +
                positionResult.regeocode.addressComponent.street +
                positionResult.regeocode.addressComponent.streetNumber,
              lng: positionResult.position.lng,
              lat: positionResult.position.lat,
            })
            this.address = positionResult.address
          })
          if (this.lat && this.lng) {
            mapConfig.center = [this.lng, this.lat]
            positionPicker.start([this.lng, this.lat])
            map.panBy(0, 1)
          }
          AMap.plugin('AMap.Geolocation', function () {
            var geolocation = new AMap.Geolocation({
              enableHighAccuracy: true, //是否使用高精度定位，默认:true
              timeout: 10000, //超过10秒后停止定位，默认：无穷大
              maximumAge: 0, //定位结果缓存0毫秒，默认：0
              convert: true, //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
              showButton: true, //显示定位按钮，默认：true
              buttonPosition: 'LB', //定位按钮停靠位置，默认：'LB'，左下角
              buttonOffset: new AMap.Pixel(10, 20), //定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
              showMarker: true, //定位成功后在定位到的位置显示点标记，默认：true
              showCircle: true, //定位成功后用圆圈表示定位精度范围，默认：true
              panToLocation: true, //定位成功后将定位到的位置作为地图中心点，默认：true
              zoomToAccuracy: true, //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
            })

            geolocation.getCurrentPosition()
            //console.log(that.frontAreaCode);
            if (that.frontAreaCode == undefined || that.frontAreaCode == '') {
              console.log('开始定位')
              AMap.event.addListener(geolocation, 'complete', onComplete)
              // AMap.event.addListener(geolocation, 'error', onError)
            }
            function onGdWebView(data){
              const {frontLongitude:lon,frontDimension:lat,frontName:name} = data
              return routerWebViewGd({lon,lat,name})
            }
            function onComplete(data) {
              // data是具体的定位信息
              console.log('定位成功')
              var x = data.position.lng
              var y = data.position.lat
              uni.setStorageSync('lng', x)
              uni.setStorageSync('lat', y)
              const markers = []
              const params = { distance: 3000, lng: x, lat: y }
              getFrontList(params).then((res) => {
                if (res.success) {
                  const list = res.result
                  for (var i = 0; i < list.length; i++) {
                    var marker = new AMap.Marker({
                      position: [list[i].frontLongitude, list[i].frontDimension],
                      icon: new AMap.Icon({
                        image: '/static/img/marker.png',
                        size: new AMap.Size(30, 30), //图标大小
                        imageSize: new AMap.Size(30, 30),
                      }),
                      offset: new AMap.Pixel(-10, -10),
                    })
                    marker.info = list[i]
                    if (map) marker.setMap(map)

                    // label默认蓝框白底左上角显示，样式className为：amap-marker-label
                    // marker.setLabel({
                    // 	offset: new AMap.Pixel(0, -30), //设置文本标注偏移量
                    // 	content: "<div class='info' style='padding: 3px 5px;'>" + list[i].frontName + '</div>', //设置文本标注内容
                    // 	direction: 'center' //设置文本标注方位
                    // });
                    //marker.positon = list[i].id;
                    //鼠标点击marker弹出自定义的信息窗体
                    marker.on('click', function (e) {
                      //console.log(e)
                      // that.isShow= true;
                      // that.info = e.target.info;
                      // gpGpinfo(that.info.gpinfoId).then(res => {
                      // 	if(res.success)
                      // 	{
                      // 		that.gpinfoName = res.result.gpinfoName;
                      // 	}
                      // });
                      openInfo(e.target.info)

                    })
                    markers.push(marker)
                    map.setCenter([x, y])
                  }
                }
              })
              var marker = new AMap.Marker({
                position: [x, y],
                icon: new AMap.Icon({
                  image: '/static/img/mys.png',
                  size: new AMap.Size(30, 30), //图标大小
                  imageSize: new AMap.Size(30, 30),
                }),
                offset: new AMap.Pixel(-10, -10),
              })
              marker.setMap(map)
            }
            //在指定位置打开信息窗体
            function openInfo(el) {
              onGdWebView(el)
              //构建信息窗体中显示的内容
              //console.log(']]]',el);
              var info = []

              info.push('<div style="padding:7px 0px 0px 0px;">')
              info.push(
                "<a style='text-decoration:none; color: #000;' href=\"/#/pages/front/front?id=" +
                  el.id +
                  '"><h4>' +
                  el.frontName +
                  '</h4>'
              )
              info.push(
                "<p class='input-item' style='font-size: 12px!important'>容纳人数：" +
                  el.frontCapacity +
                  '人</p>'
              )
              info.push(
                "<p class='input-item' style='font-size: 12px!important'>地址：" +
                  el.frontAddress +
                  '</p>'
              )
              info.push('</a></div>')
              infoWindow = new AMap.InfoWindow({
                content: info.join(''), //使用默认信息窗体框样式，显示信息内容
              })

              infoWindow.open(map, [el.frontLongitude, el.frontDimension])
            }
            function onError(data) {
              // 定位出错
              console.log('定位出错')
              var x = that.center[0]
              var y = that.center[1]
              map.setCenter([x, y])
              const markers = []
              const params = { distance: 3000, lng: x, lat: y }
              getFrontList(params).then((res) => {
                if (res.success) {
                  const list = res.result
                  for (var i = 0; i < list.length; i++) {
                    var marker = new AMap.Marker({
                      position: [list[i].frontLongitude, list[i].frontDimension],
                      icon: new AMap.Icon({
                        image: '/static/img/marker.png',
                        size: new AMap.Size(30, 30), //图标大小
                        imageSize: new AMap.Size(30, 30),
                      }),
                      offset: new AMap.Pixel(-10, -10),
                    })
                    marker.info = list[i]
                    marker.setMap(map)

                    // label默认蓝框白底左上角显示，样式className为：amap-marker-label
                    // marker.setLabel({
                    //   offset: new AMap.Pixel(0, -30), //设置文本标注偏移量
                    //   content:
                    //     "<div class='info' style='padding: 3px 5px;'>" +
                    //     list[i].frontName +
                    //     '</div>', //设置文本标注内容
                    //   direction: 'center', //设置文本标注方位
                    // })
                    //marker.positon = list[i].id;
                    //鼠标点击marker弹出自定义的信息窗体
                    marker.on('click', function (e) {
                      console.log(e)
                      that.isShow = true
                      that.info = e.target.info
                      gpGpinfo(that.info.gpinfoId).then((res) => {
                        if (res.success) {
                          that.gpinfoName = res.result.gpinfoName
                        }
                      })
                    })
                    markers.push(marker)
                    map.setCenter([x, y])
                  }
                }
              })
              var marker = new AMap.Marker({
                position: [x, y],
                icon: new AMap.Icon({
                  image: '/static/img/mys.png',
                  size: new AMap.Size(30, 30), //图标大小
                  imageSize: new AMap.Size(30, 30),
                }),
                offset: new AMap.Pixel(-10, -10),
              })
              marker.setMap(map)
            }
          })
        })
      },
    },
  }
</script>

<style scoped lang="scss">
  .map-box {
    margin: 30rpx 0;
    width: 100%;
    height: 500rpx;
    border-radius: 10rpx !important;
    overflow: hidden;
    #map-box {
      width: 100%;
      height: 100%;
    }
  }
  ._map-box {
    width: 100%;
    height: 100%;
    text-align: center;
    font-size: 30rpx;
    //padding-top: 300rpx;
  }
</style>
